package com.zjlab.georeceive;

import cn.hutool.core.util.ObjectUtil;
import com.zjlab.georeceive.bean.AreaBase;
import com.zjlab.sandtable.SandTableUdp;
import com.zjlab.sandtable.bean.AreaBaseInfo;
import com.zjlab.sandtable.bean.TurnOffCarLightInfo;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.concurrent.atomic.AtomicReference;

/**
 * geo处理类
 *
 * @author xue
 * @create 2022-11-07 16:25
 */
@Component
public class GeoProcessor {

    private final SandTableUdp sandTableUdp;

    public GeoProcessor(SandTableUdp sandTableUdp) {
        this.sandTableUdp = sandTableUdp;
    }

    private final AtomicReference<AreaBase> areaBaseAtomic = new AtomicReference<>(null);


    public void geoSwitch(Boolean input) {
        if (input) {
            areaBaseAtomic.set(new AreaBase());
        } else {
            areaBaseAtomic.set(null);
            sandTableUdp.sendInfo(new TurnOffCarLightInfo(1));
        }
    }


    public void receiveAreaBase(AreaBase areaBase) {
        AreaBase beforeAreaBase = areaBaseAtomic.get();
        if (ObjectUtil.isNotNull(beforeAreaBase) && !areaBase.equals(beforeAreaBase)) {
            areaBaseAtomic.set(areaBase);
            sendAreaToSandTable(areaBase);
        }
    }

    private void sendAreaToSandTable(AreaBase areaBase) {
        double lonDouble = BigDecimal.valueOf(areaBase.getLon()).
                divide(BigDecimal.valueOf(10000000), 20, BigDecimal.ROUND_HALF_UP)
                .add(BigDecimal.valueOf(119))
                .doubleValue();
        double latDouble = BigDecimal.valueOf(areaBase.getLat())
                .divide(BigDecimal.valueOf(10000000), 20, BigDecimal.ROUND_HALF_UP)
                .add(BigDecimal.valueOf(30))
                .doubleValue();
        sandTableUdp.sendInfo(new AreaBaseInfo(
                areaBase.getStationId(),
                latDouble,
                lonDouble,
                Double.parseDouble(String.valueOf(areaBase.getLdm())),
                Double.parseDouble(String.valueOf(areaBase.getSdm()))
        ));
    }


}
